package com.mobilesalon.activity;

import java.io.File;
import java.util.Calendar;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.mobilesalon.MobileSalonApplication;
import com.mobilesalon.MobileSalonFactory;
import com.mobilesalon.R;
import com.mobilesalon.business.ConfigurationException;
import com.mobilesalon.business.PreferencesManager;
import com.mobilesalon.business.ServiceClientReportManager;
import com.mobilesalon.provider.ServiceClientContract.Service;
import com.mobilesalon.report.engine.ReportException;
import com.mobilesalon.report.model.ReportBean;
import com.mobilesalon.tools.DateTools;
import com.mobilesalon.tools.MyCursorAdapter;
import com.mobilesalon.widget.swipe.SwipeListActivity;

public class MonthReport extends SwipeListActivity implements Iconable{

	private static final String TAG = MonthReport.class.getName();

	static final int PICK_CONTACT = 1;
	static final int SHOW_SERICE_DIALOG = 2;

	protected ServiceClientReportManager serviceClientReportManager;
	private PreferencesManager preferencesManager;

	protected TextView titleTextView;
	protected TextView totalAmountTextView;

	protected Calendar current;

	// report data
	protected ReportBean report;

	private String reportTitle;

	//
	// Lifecycle
	//
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.e(TAG, "Start Activity");
		super.onCreate(savedInstanceState);

		// business services
		serviceClientReportManager = MobileSalonFactory.getServiceClientReportManager();
		preferencesManager = MobileSalonFactory.getPreferencesManager();

		// UI
		setContentView(this.getContentView());
		titleTextView = (TextView) this.findViewById(R.id.service_month_report_text_header);
		totalAmountTextView = (TextView) this.findViewById(R.id.service_month_report_amount_total);

		this.current = Calendar.getInstance();
		this.displayReport();

	}

	protected int getContentView() {
		return R.layout.service_month_report;
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	//
	// Swipe management
	//
	public void swipeLeft() {
		current.add(Calendar.MONTH, +1);
		this.displayReport();
	}

	public void swipeRight() {
		current.add(Calendar.MONTH, -1);
		this.displayReport();
	}

	//
	// Report content
	//

	protected void setReportTitle(String reportTitle) {
		this.reportTitle = reportTitle;
		titleTextView.setText(reportTitle);
	}

	protected void displayReport() {
		String month = DateTools.MONTH_DATEFORMAT.format(current.getTime());
		this.setReportTitle(String.format(getString(R.string.service_month_report_title), month));

		Log.d(TAG, "Display report for date:" + month);

		try {
			report = serviceClientReportManager.fetchMonthAppointments(this.current);
		} catch (ConfigurationException e) {
			Toast.makeText(MobileSalonFactory.getContext(), e.getErrorMessageRessourceId(),
					Toast.LENGTH_LONG).show();
			return;
		}

		float totalAmount = 0;
		Cursor cursor = report.getMonthReportCursor();
		startManagingCursor(cursor);

		cursor.moveToPosition(-1);
		while (cursor.moveToNext()) {
			totalAmount = totalAmount + cursor.getFloat(cursor.getColumnIndex("sum"));
		}

		totalAmountTextView.setText("" + report.getSumAmountService());

		// Create a mapping between database columns and layout fields
		String[] from = new String[] { Service.SERVICE_NAME, "count", "sum" };
		int[] to = new int[] { R.id.service_month_report_row_service_name,
				R.id.service_month_report_row_count, R.id.service_month_report_row_sum };

		// Create a cursor adapter and set it to display using a row layout
		MyCursorAdapter adapter = new MyCursorAdapter(this, R.layout.service_month_report_row,
				cursor, from, to);

		setListAdapter(adapter);
	}

	//
	// Menu behavior
	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_report, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_report_export_mail:
			try {
				File f = serviceClientReportManager.exportMonthReport(this.report);
				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.putExtra(Intent.EXTRA_SUBJECT, this.reportTitle);
				intent.putExtra(Intent.EXTRA_EMAIL,
						new String[] { preferencesManager.getReportsRecipents() });
				intent.putExtra(Intent.EXTRA_TEXT, "");
				intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + f.getAbsolutePath()));
				intent.setType("text/csv");
				f.canRead();
				startActivity(Intent.createChooser(intent, "Send mail"));
			} catch (ReportException e) {
				Toast.makeText(MobileSalonFactory.getContext(),
						getString(R.string.report_exception_sd_card_not_availabe),
						Toast.LENGTH_LONG).show();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public int getIconResource() {
		return  R.drawable.icon;
	}

	public String getIconName() {
		return MobileSalonApplication.getAppContext().getString(R.string.service_month_report_icon);
	}
}
